package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 壮哥
 * @Date 2021/9/29/16:51
 */
@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDTO dto) {
        String phone = dto.getPhone();
        String password = dto.getPassword();
        Integer equipmentId = dto.getEquipmentId();
        if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(password)) {
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
//            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
                String inputPwd = DigestUtils.md5DigestAsHex((password+apUser.getSalt()).getBytes());
                if (!inputPwd.equals(apUser.getPassword())) {
                    CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码不对");
                }
                if (apUser.getStatus()) {
                    CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
                }
                String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                Map result = new HashMap<>();
                result.put("token", token);
                apUser.setSalt("");
                apUser.setPassword("");
                result.put("user", apUser);
                return ResponseResult.okResult(result);

        } else {
            if (equipmentId == null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "无设备ID");
            }
            String token = AppJwtUtil.getToken(0L);
            Map result = new HashMap<>();
            result.put("token", token);
            return ResponseResult.okResult(result);
        }

    }

}
